package com.yenlien.traceyun.plant.service;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.plant.dao.ArticleDao;
import com.yenlien.traceyun.plant.dao.FruitBannerDao;
import com.yenlien.traceyun.plant.entity.Article;
import com.yenlien.traceyun.plant.entity.FruitBanner;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.yenlien.traceyun.plant.utils.Tools.DATE_TIME_FORMATTER;

@Service
public class CMSService {

    @Autowired
    private FruitBannerDao bannerDao;
    @Autowired
    private ArticleDao articleDao;


    public FruitBanner saveBanner(FruitBanner fruitBanner) {
        if (StringUtils.isBlank(fruitBanner.getId())) {
            fruitBanner.setCreateTime(LocalDateTime.now().format(DATE_TIME_FORMATTER));
            fruitBanner.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        }
        return bannerDao.save(fruitBanner);
    }

    public Article saveArticle(Article article) {
        String dateTime = LocalDateTime.now().format(DATE_TIME_FORMATTER);
        if(StringUtils.isBlank(article.getId())){
            article.setViewNum(0);
            article.setState("1");
            article.setCreateTime(dateTime);
            article.setLastUpdateTime(dateTime);
        }else {
            article.setLastUpdateTime(dateTime);
            if("2".equals(article.getState())){
                article.setPublisher(UserAuthUtil.getLoginUser().getUsername());
            }
        }
        return articleDao.save(article);
    }



    public Page<FruitBanner> findBannerList(FruitBanner fruitBanner) {
        Pageable pageable = PageRequest.of(fruitBanner.getPage(), fruitBanner.getPageSize(), Sort.Direction.DESC, ("createTime"));
        return bannerDao.findAll((Root<FruitBanner> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            list.add(cb.equal(root.get("companyId"), UserAuthUtil.getLoginUser().getCompanyId()));
            if(StringUtils.isNotBlank(fruitBanner.getType()))
                list.add(cb.equal(root.get("type"), fruitBanner.getType()));
            return cb.and(list.toArray(new Predicate[list.size()]));
        }, pageable);
    }


    public Page<Article> findContentList(Article article) {
        Pageable pageable = PageRequest.of(article.getPage(), article.getPageSize(), Sort.Direction.DESC, ("createTime"));
        return articleDao.findAll((Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> listAnd = new ArrayList<>();
            List<Predicate> listOr = new ArrayList<>();
            listAnd.add(cb.equal(root.get("companyId"), UserAuthUtil.getLoginUser().getCompanyId()));
            if(StringUtils.isNotBlank(article.getType()))
                listAnd.add(cb.equal(root.get("type"), article.getType()));
            if(StringUtils.isNotBlank(article.getState()))
                listAnd.add(cb.equal(root.get("state"), article.getState()));
            if(article.getHomeShow() != null)
                listAnd.add(cb.equal(root.get("homeShow"), article.getHomeShow()));
            if(article.getHotspot() != null)
                listAnd.add(cb.equal(root.get("hotspot"), article.getHotspot()));
            if(StringUtils.isNotBlank(article.getPublisher()))
                listAnd.add(cb.like(root.get("publisher"), "%" +article.getPublisher() + "%"));
            return cb.and(listAnd.toArray(new Predicate[listAnd.size()]));
//            String now = LocalDateTime.now().format(DATE_TIME_FORMATTER);
//            listOr.add(cb.equal(root.get("timely"), "1"));
//            listOr.add(cb.greaterThanOrEqualTo(root.get("publishTimeStart"), now));
//            listOr.add(cb.lessThanOrEqualTo(root.get("publishTimeEnd"), now));
//            Predicate preOr = cb.or(listOr.toArray(new Predicate[listOr.size()]));
//            return query.where(preAnd, preOr).getRestriction();
        }, pageable);
    }



    public List<JSONObject> findArticleDown(String companyId) {
       if(StringUtils.isBlank(companyId))
           companyId = UserAuthUtil.getLoginUser().getCompanyId();
        return articleDao.getIdNameByState(companyId);
    }

    public Article state(String id, String state) {
        Article article = articleDao.findById(id).orElseThrow(() -> new BusinessException("该文章不存在"));
        article.setState(state);
        return articleDao.save(article);
    }

    public Article findArticleById(String id) {
        Article article = articleDao.findById(id).orElseThrow(() -> new BusinessException("该文章不存在"));
        Integer viewNum = article.getViewNum();
        if(viewNum == null)
            viewNum = 1;
        else
            viewNum += 1;
        article.setViewNum(viewNum);
        return articleDao.save(article);
    }




}
